<?php

namespace app\api\service;

class CheckPoint
{
    private static $coordArray;
    private static $vertx = [];
    private static $verty = [];

    /**
     * 设置坐标区域
     * @param mixed $coordArray
     */
    public static function setCoordArray(array $coordArray)
    {
        self::$coordArray = $coordArray;
    }

    /**
     * 验证区域范围
     * @param array $coordArray
     * @return bool
     */
    public static function isCityCenter(array $coordArray)
    {
        if (!self::vaildatePoint($coordArray)) {
            return false;
        }
        return self::pnpoly(count(self::$coordArray), $coordArray['1'], $coordArray['0']);
    }

    /**
     * 比较区域坐标
     * @param $nvert
     * @param $testx
     * @param $testy
     * @return bool
     */
    private static function pnpoly($nvert, $testx, $testy)
    {
        $c = false;
        for ($i = 0, $j = $nvert - 1; $i < $nvert; $j = $i++) {
            if (((self::$verty[$i] > $testy) != (self::$verty[$j] > $testy)) && ($testx < (self::$vertx[$j] - self::$vertx[$i]) * ($testy - self::$verty[$i]) / (self::$verty[$j] - self::$verty[$i]) + self::$vertx[$i]))
                $c = !$c;
        }
        return $c;
    }

    /**
     * 验证坐标
     * @param array $pointArray
     * @return bool
     */
    private static function vaildatePoint(array $pointArray)
    {
        $maxY = $maxX = 0;
        $minY = $minX = 9999;
        foreach (self::$coordArray as $item) {
            if ($item['1'] > $maxX) $maxX = $item['1'];
            if ($item['1'] < $minX) $minX = $item['1'];
            if ($item['0'] > $maxY) $maxY = $item['0'];
            if ($item['0'] < $minY) $minY = $item['0'];
            self::$vertx[] = $item['1'];
            self::$verty[] = $item['0'];
        }
        if ($pointArray['1'] < $minX || $pointArray['1'] > $maxX || $pointArray['0'] < $minY || $pointArray['0'] > $maxY) {
            return false;
        }
        return true;
    }
}